<template>
  <div class="form-container" v-loading="loading">
    <el-form size="mini" ref="form" :model="form" :rules="rules" label-width="120px">
      <!-- 手机号 -->
      <el-form-item v-if="mode === 'add'" prop="phone" label="手机号">
        <el-input v-model="form.phone" placeholder="请填写手机号"></el-input>
        <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 非会员 -->
    <div v-if="companyInfo && companyInfo.IsFjUser === 0" class="not-vip">未在Feijiu网检索到该用户，请引导用户使用废旧网小程序注册账号</div>
    <!-- 企业详情 -->
    <template v-if="companyInfo && companyInfo.IsFjUser === 1">
      <div class="info">
        <div class="item">
          <div class="label">企业名称：</div>
          <div class="value">{{ companyInfo.comName }}</div>
        </div>
        <div class="item">
          <div class="label">联系人：</div>
          <div class="value">{{ companyInfo.linkMan }}</div>
        </div>
        <div class="item">
          <div class="label">联系电话：</div>
          <div class="value">{{ companyInfo.phone }}</div>
        </div>
        <div class="item">
          <div class="label">Feijiu会员：</div>
          <div class="value">{{ companyInfo.vipName }}({{ companyInfo.vipSTime }} - {{ companyInfo.vipETime }})</div>
        </div>
      </div>
      <el-form size="mini" ref="form2" :model="form2" :rules="rules2" label-width="120px">
        <!-- 手机号 -->
        <el-form-item prop="is_add_wx" label="是否已加微信">
          <el-radio-group v-model="form2.is_add_wx">
            <el-radio :label="1">否</el-radio>
            <el-radio :label="2">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="sign_method" label="签约方式">
          <el-radio-group :disabled="mode === 'edit'" v-model="form2.sign_method">
            <el-radio :label="1">线上签约</el-radio>
            <el-radio :label="2">线下签约</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="files" label="上传合同">
          <el-upload list-type="picture" class="upload-demo" accept="image/jpeg, image/png, .pdf" action="" :before-upload="beforeUpload" :on-preview="handlePreview" :on-remove="handleRemove" multiple :limit="10" :on-exceed="handleExceed" :file-list="uploadFileList" :http-request="handleUpload">
            <el-button size="mini" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持上传pdf，jpg，png格式文件，最大不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="sign_time" label="签约时间">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form2.sign_time" type="datetime" placeholder="请选择签约时间"> </el-date-picker>
        </el-form-item>
        <el-form-item prop="follow_id" label="跟进人">
          <el-select v-model="form2.follow_id" placeholder="请选择跟进人">
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item>
          <el-button size="mini" @click="onCancel">取消</el-button>
          <el-button size="mini" type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </template>
  </div>
</template>
<script>
import { apiUserSelect, apiSignSearchPhone, apiSignFileUpload, apiSignUserAdd, apiSignUserDetail, apiSignUserEdit } from '@/api/assetsDisposal'
import { isMobile } from '@/utils/validate.js'

export default {
  props: {
    id: String,
    mode: String,
  },
  data() {
    var validaMobile = (rule, value, callback) => {
      if (value && !isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      showPreview: false,
      previewFile: {},
      step: 'phone',
      form: {
        phone: '',
      },
      rules: {
        phone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' },
          { validator: validaMobile, trigger: 'blur' },
        ],
      },
      form2: {
        is_add_wx: '',
        sign_method: '',
        files: [],
        sign_time: '',
        follow_id: '',
        follow_name: '',
      },
      rules2: {
        is_add_wx: [{ required: true, message: '请选择是否添加微信', trigger: 'blur' }],
        sign_method: [{ required: true, message: '请选择签约方式', trigger: 'blur' }],
        files: [{ required: true, message: '请上传合同', trigger: 'blur' }],
        sign_time: [{ required: true, message: '请选择签约时间', trigger: 'blur' }],
        follow_id: [{ required: true, message: '请选择跟进人', trigger: 'blur' }],
      },
      loading: false,
      companyInfo: {},
      uploadFileList: [],
      fileList: [],
      userList: [],
      pdfCover: 'https://recycleimg.feijiu.net/zft/mini/1706230913392.png',
    }
  },
  computed: {},
  mounted() {
    this.getDepartmentUser()
    this.getDetail()
  },
  methods: {
    // 获取人员下拉
    getDepartmentUser() {
      apiUserSelect().then((res) => {
        this.userList = res.data
      })
    },
    timeFormat(data) {
      return `${data.getFullYear()}-${data.getMonth() + 1}-${data.getDate()} ${data.getHours()}:${data.getMinutes()}:${data.getSeconds()}`
    },
    // 获取详情
    getDetail() {
      if (this.mode === 'add') {
        let userId = localStorage.getItem('id')
        this.form2.follow_id = userId
        this.form2.sign_time = this.timeFormat(new Date())
        return
      }
      const info = {
        id: this.id,
      }
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      apiSignUserDetail(formData).then((res) => {
        console.log(res)
        if (res.code !== 200) {
          return
        }
        this.companyInfo = {
          IsFjUser: 1,
          comName: res.data.com_name,
          linkMan: res.data.user_name,
          vipName: res.data.vip_name,
          vipSTime: res.data.vip_start_time,
          vipETime: res.data.vip_end_time,
          phone: res.data.phone,
        }
        this.form.phone = res.data.user_phone
        for (let key in this.form2) {
          if (key in res.data) {
            this.form2[key] = res.data[key]
          }
        }
        this.fileList = this.form2.files.map((item) => {
          const arr = item.split('.')
          const type = arr[arr.length - 1]
          if (type === 'pdf') {
            return {
              name: item,
              url: this.pdfCover,
              type: 'application/pdf',
              fileUrl: item,
            }
          } else {
            return {
              name: item,
              url: item,
              type: 'image/',
              fileUrl: item,
            }
          }
        })

        this.uploadFileList = [...this.fileList]
      })
    },
    // 保存
    onSubmit() {
      this.$refs.form2.validate((flag) => {
        if (flag) {
          this.loading = true
          this.form2.follow_name = this.userList.find((item) => item.id === this.form2.follow_id).name

          const formData = new FormData()
          for (let key in this.form2) {
            formData.set(key, this.form2[key])
          }

          if (this.mode === 'add') {
            for (let key in this.companyInfo) {
              if (key !== 'is_sign' && key !== 'IsFjUser') formData.set(key, this.companyInfo[key])
            }
            formData.set('send_to_feijiu', 1)

            apiSignUserAdd(formData)
              .then((res) => {
                this.loading = false
                if (res.code !== 200) {
                  return
                }
                this.$message({
                  message: '操作成功！',
                  type: 'success',
                })
                setTimeout(() => {
                  this.$emit('refresh')
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          } else if (this.mode === 'edit') {
            formData.set('id', this.id)
            formData.set('send_to_feijiu', 1)
            apiSignUserEdit(formData)
              .then((res) => {
                this.loading = false
                if (res.code !== 200) {
                  return
                }
                this.$message({
                  message: '操作成功！',
                  type: 'success',
                })
                setTimeout(() => {
                  this.$emit('refresh')
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          }
        }
      })
    },
    // 取消
    onCancel() {
      this.$emit('close')
    },
    // 查询手机号
    handleQuery() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const info = { phone: this.form.phone }
          const formData = new FormData()
          for (let key in info) {
            formData.set(key, info[key])
          }
          apiSignSearchPhone(formData).then((res) => {
            this.companyInfo = res.data
          })
        }
      })
    },
    // 文件上传
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.form2.files = this.fileList.map((item) => item.fileUrl)
    },
    handlePreview(file) {
      window.open(file.fileUrl)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt10M
    },
    handleUpload(file) {
      const info = { file: file.file }
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      apiSignFileUpload(formData).then((res) => {
        if (res.code === 200) {
          const type = file.file.type
          let url = res.data.url
          if (type === 'application/pdf') {
            url = this.pdfCover
          }
          this.fileList.push({
            name: file.file.name,
            url,
            type,
            fileUrl: res.data.url,
          })
          this.form2.files = this.fileList.map((item) => item.fileUrl)
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.form-container {
  padding: 0 16px;
}
.el-input {
  width: auto !important;
  margin-right: 10px !important;
}
.not-vip {
  margin-left: 50px;
  color: #f56c6c;
}
.info {
  background: #efefef;
  padding: 12px 16px;
  color: #333333;
  margin-bottom: 16px;
  .item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    line-height: 2;
    .label {
      width: 100px;
    }
  }
}

.preview {
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    max-height: 500px;
    max-width: 100%;
  }
}
</style>
